<template>
  <div ref="lineChartRef" class="w-1/1 h-1/1"></div>
</template>
<script setup lang="ts">
import type { EChartsOption } from "echarts";
import echarts from "@/plugins/echarts";
const lineChartRef = ref<ElRef>();
let echartRef: Nullable<echarts.ECharts> = null;

const props = defineProps({
  title: {
    type: String,
    default: "",
  },
  // 显示数据规则
  formatter: {
    type: String,
    default: "",
  },
  // 折线图是否平滑显示
  smoothType:{
    type:Boolean,
    default: false
  },
  options: {
    type: Object,
    default() {
      return {};
    },
  },
});
watch(
  () => props.options,
  () => {
    setOptions();
  },
  { deep: true }
);

onMounted(() => {
  initChart();
});
onUnmounted(() => {
  echartRef?.dispose;
});
const initChart = () => {
  if (unref(lineChartRef) && props.options) {
    echartRef = echarts.init(unref(lineChartRef) as unknown as HTMLElement);
    setOptions();
    window.onresize = function () {
      echartRef?.resize();
    };
  }
};

const setOptions = () => {
  if (unref(lineChartRef) && props.options) {
    const _legendData: string[] = [];
    const _seriesData: any = [];
    if (props.options.seriesData && props.options.seriesData.length > 0) {
      props.options.seriesData.forEach((item: any) => {
        _legendData.push(item.name);
        _seriesData.push({
          data: item.data,
          name: item.name,
          type: "line",
          smooth: props.smoothType, // 是否平滑曲线显示
          label: {
            show: true,
            position: "top",
            formatter: props.formatter,
          },
        });
      });
    }

    const _echartOption: EChartsOption = {
      title: {
        text: props.title,
        left: "left",
      },
      grid: {
        left: "10px",
        right: "100px",
        bottom: "0",
        containLabel: true,
      },
      legend: {
        orient: "vertical",
        left: "right",
        align: "left",
        top: "50px",
        data: _legendData,
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: props.options.xAxisData,
      },
      tooltip: {
        trigger: "axis",
      },
      yAxis: {
        type: "value",
      },
      series: _seriesData,
    };
    echartRef?.setOption(_echartOption);
  }
};
</script>
